package cn.sixmillions.yuqueblog.service.impl;

import cn.hutool.http.HttpRequest;
import cn.sixmillions.yuqueblog.config.YuQueProperties;
import cn.sixmillions.yuqueblog.entity.Doc;
import cn.sixmillions.yuqueblog.entity.DocDetail;
import cn.sixmillions.yuqueblog.service.IDocService;
import cn.sixmillions.yuqueblog.utils.HtmlUtil;
import cn.sixmillions.yuqueblog.utils.RedisUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static cn.sixmillions.yuqueblog.common.constant.YuQueConstant.*;

/**
 * @description: 知识库接口实现
 * @author: sixmillions
 * @since: 2021/12/12
 **/
@Service
@Slf4j
public class DocServiceImpl implements IDocService {

    @Autowired
    private YuQueProperties conf;

    @Override
    public List<Doc> getDocs(String namespace) {
        String cacheKey = String.format(REPO_DOCS_CACHE_KEY, namespace);
        String docsCache = RedisUtil.StringOps.get(cacheKey);
        if (StringUtils.isNotBlank(docsCache)) {
            //从缓存获取
            return JSON.parseArray(docsCache, Doc.class);
        }
        // 请求语雀API
        String requestUrl = String.format(REPO_DOCS_URL, namespace);
        String reponseRes = HttpRequest.get(requestUrl).header(AUTH_HEADER, conf.getToken()).execute().body();
        String docs = JSON.parseObject(reponseRes).getString("data");
        RedisUtil.StringOps.set(cacheKey, docs);
        return JSON.parseArray(docs, Doc.class);
    }

    @Override
    public DocDetail detail(String namespace, String slug) {
        String cacheKey = String.format(DOC_CACHE_KEY, namespace, slug);
        String docCache = RedisUtil.StringOps.get(cacheKey);
        if (StringUtils.isNotBlank(docCache)) {
            //从缓存获取
            return JSON.parseObject(docCache, DocDetail.class);
        }
        // 请求语雀API
        String requestUrl = String.format(DOC_URL, namespace, slug);
        String reponseRes = HttpRequest.get(requestUrl).header(AUTH_HEADER, conf.getToken()).execute().body();
        String doc = JSON.parseObject(reponseRes).getString("data");
        DocDetail docDetail = JSON.parseObject(doc, DocDetail.class);
        //重写html中的图片链接
        docDetail.setBodyHtml(HtmlUtil.overwriteImgSrc(docDetail.getBodyHtml()));
        RedisUtil.StringOps.set(cacheKey, JSON.toJSONString(docDetail));
        return docDetail;
    }
}
